import datetime
import sys
from typing import List

from models import Order, Shift, User, db
from PySide6.QtCore import QCoreApplication, QDate, QSize, Qt, QTime
from PySide6.QtGui import QIcon, QPixmap
from PySide6.QtWidgets import (QApplication, QComboBox, QDateEdit,
                               QGraphicsView, QGraphicsWidget, QHBoxLayout,
                               QInputDialog, QLabel, QLineEdit, QMainWindow,
                               QMessageBox, QPushButton, QTableWidget,
                               QTableWidgetItem, QTabWidget, QTextEdit,
                               QTimeEdit, QVBoxLayout, QWidget)

order_statuses = {'ready': 'Готов', 'preparing': 'Готовится', 'paid': 'Оплачен', 'placed': 'Заказан'}

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.logo = QLabel()        
        pixmap = QPixmap('./Sezon.png')
        self.logo.setPixmap(pixmap)
        self.setFixedSize(QSize(1000,800))
        self.setWindowTitle('Окно авторизации')
        self.setWindowIcon(pixmap)
        self.setWindowIconText('Sezon')
        label = QLabel('Выполните вход')
        label.setAlignment(Qt.AlignCenter)
        self.login_btn = QPushButton('Войти')
        self.exit_btn = QPushButton('Выход')
        self.exit_btn.clicked.connect(QCoreApplication.instance().quit)
        
        self.login_btn.clicked.connect(lambda: self._open_login_window())
        
        btn_layout = QVBoxLayout()
        btn_layout.addWidget(label)
        btn_layout.addWidget(self.login_btn)
        btn_layout.addWidget(self.exit_btn)
        
        self.login_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        self.exit_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        
        layout = QHBoxLayout()
        layout.addWidget(self.logo)
        layout.addLayout(btn_layout)
        
        self.container = QWidget()
        self.container.setStyleSheet('background-color: #fff; color: #000;')
        self.container.setLayout(layout)
        self.setCentralWidget(self.container)

    def _open_login_window(self):
        self.hide()
        self.login_window = LoginWindow(parent=self)
        self.login_window.show()
        
class LoginWindow(QWidget):
    user: User
    def __init__(self,parent):
        super().__init__()
        self.user = None
        self.logo = QLabel()        
        pixmap = QPixmap('./Sezon.png')
        self.logo.setPixmap(pixmap)
        self.setWindowIcon(QIcon('./Sezon.png'))
        self.setFixedSize(QSize(1000, 800))
        self.setWindowTitle("Окно авторизации")
        self.main_window = parent
        self.login_field = QLineEdit()
        self.login_field.setPlaceholderText('Логин')
        self.pass_field = QLineEdit()
        self.pass_field.setPlaceholderText('Пароль')
        self.pass_field.setEchoMode(QLineEdit.EchoMode.Password)
        login_btn = QPushButton('Войти')
        login_btn.clicked.connect(lambda: self._login(self.login_field.text(), self.pass_field.text()))
        back_btn = QPushButton('Назад')
        back_btn.clicked.connect(self._back)
        
        self.login_field.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        self.pass_field.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        login_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        
        
        btn_layout = QVBoxLayout()
        btn_layout.addWidget(self.login_field)
        btn_layout.addWidget(self.pass_field)
        btn_layout.addWidget(login_btn)
        btn_layout.addWidget(back_btn)
        btn_widget = QWidget(self)
        btn_widget.setFixedHeight(300)
        btn_widget.setLayout(btn_layout)
        btn_widget.setStyleSheet('background-color: rgb(118, 227, 131); color: #000;')
        
        layout = QHBoxLayout()
        layout.addWidget(self.logo)
        layout.addWidget(btn_widget)
        self.setStyleSheet('background-color: #fff; color: #000;')
        self.setLayout(layout)
        
    def _login(self, login: str, password: str):
        db.connect(reuse_if_open=True)
        user = User.select().where((User.username==login) & (User.password==password)).first()
        db.close()
        if user and user.fired:
            QMessageBox.warning(self, 'Error', 'Паркер, ты уволен!')
            return
        if user:
            self.hide()
            self.user = user
            self.role = user.role
            if self.role == 'admin':
                self.admin_window = AdminWindow(parent=self)
                self.admin_window.show()
            elif self.role == 'cook':
                self.cook_window = CookWindow(parent=self)
                self.cook_window.show()
            elif self.role == 'waiter':
                self.waiter_window = WaiterWindow(parent=self)
                self.waiter_window.show()
            self.login_field.setText('')
            self.pass_field.setText('')
        else:
            message_box = QMessageBox()
            message_box.setWindowTitle('Ошибка!')
            message_box.setText('Неверный логин или пароль или роль')
            message_box.setIcon(QMessageBox.Icon.Warning)
            message_box.exec()
    
    def _back(self):
        self.main_window.show()
        self.close()
        
    def _get_shifts(self):
        db.connect()
        shifts = Shift.select()
        db.close()
        return shifts

def get_logo():
    logo = QLabel()        
    pixmap = QPixmap('./Sezon.png')
    logo.setPixmap(pixmap)
    return logo
    
class AdminWindow(QWidget):
    def __init__(self, parent: LoginWindow):
        super().__init__()
        self.logo = get_logo()
        self.main_window = parent
        
        self.setMinimumSize(QSize(1000, 800))
        self.setWindowTitle('Окно администратора')
        
        tabGroup = QTabWidget()
        
        users_tab = QWidget()
        users_tab_layout = QVBoxLayout()
        
        self.users_table = QTableWidget()
        self.users_table.setColumnCount(3)
        self.users_table.verticalHeader().setVisible(False)
        self.users_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.users_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self._init_users_table()
        
        self.users_table.itemSelectionChanged.connect(self._on_user_selected)
        
        user_add_btn = QPushButton('Добавить пользователя')
        user_add_btn.clicked.connect(self._add_new_user_window)
        user_add_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        
        fire_user_btn = QPushButton('Уволить пользователя')
        fire_user_btn.clicked.connect(self._fire_user)
        fire_user_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        
        
        users_tab_layout.addWidget(self.users_table)
        users_tab_layout.addWidget(user_add_btn)
        users_tab_layout.addWidget(fire_user_btn)
        users_tab.setLayout(users_tab_layout)
        
        orders_tab = QWidget()  
        self.orders_table = QTableWidget()
        self.orders_table.setColumnCount(5)
        self.orders_table.verticalHeader().setVisible(False)
        self.orders_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.orders_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self._init_orders_table()
        
        orders_layout = QVBoxLayout()
        orders_update_btn = QPushButton('Обновить')
        orders_update_btn.clicked.connect(self._init_orders_table)
        orders_update_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        orders_layout.addWidget(self.orders_table)
        orders_layout.addWidget(orders_update_btn)
        orders_tab.setLayout(orders_layout)
        
        shifts_tab = QWidget()
        self.shifts_table = QTableWidget()
        self.shifts_table.setColumnCount(3)
        self.shifts_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.shifts_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self._init_shifts_table()
        
        shifts_layout = QVBoxLayout()
        shifts_update_btn = QPushButton('Обновить')
        shifts_update_btn.clicked.connect(self._init_shifts_table)
        shifts_update_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        shift_assign_btn = QPushButton('Назначить смену')
        shift_assign_btn.clicked.connect(self._assign_shift_window)
        shift_assign_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        shift_create_btn = QPushButton('Создать смену')
        shift_create_btn.clicked.connect(self._create_shift_window)
        shift_create_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        shifts_layout.addWidget(self.shifts_table)
        shifts_layout.addWidget(shift_create_btn)
        shifts_layout.addWidget(shift_assign_btn)
        shifts_layout.addWidget(shifts_update_btn)
        shifts_tab.setLayout(shifts_layout)
        
        data_layout = QVBoxLayout()
        
        tabGroup.addTab(users_tab, 'Пользователи')
        tabGroup.addTab(orders_tab, 'Заказы')
        tabGroup.addTab(shifts_tab, 'Смены')
        tabGroup.setStyleSheet('background-color: rgb(118, 227, 131); color: #000;')
        
        data_layout.addWidget(tabGroup)
        
        exit_btn = QPushButton('Выход')
        exit_btn.clicked.connect(self._exit)
        data_layout.addWidget(exit_btn)

        layout = QHBoxLayout()
        layout.addWidget(self.logo)
        layout.addLayout(data_layout)
        self.setStyleSheet('background-color: #fff; color: #000;')
        self.setLayout(layout)
        
    def _exit(self):
        self.main_window.show()
        self.close()
    
    def _init_users_table(self):
        self.users_table.clear()
        self.users_table.setHorizontalHeaderLabels(['Имя', 'Роль', 'Уволен'])
        # db.connect()
        users = User.select(User.username, User.role, User.fired)
        db.close()
        self.users_table.setRowCount(len(users))
        for i, row in enumerate(users):
            r = [row.username, row.role, 'Да' if row.fired else 'Нет']
            for j, col in enumerate(r):
                self.users_table.setItem(i, j, QTableWidgetItem(str(col)))
                
    def _create_shift_window(self):
        self.create_shift_window = QWidget()
        self.create_shift_window.setMinimumSize(QSize(1000,800))
        self.create_shift_window.setWindowTitle('Создать смену')
        self.create_shift_window.setWindowModality(Qt.ApplicationModal)
        date_layout = QHBoxLayout()
        self.shift_date = QDateEdit()
        self.shift_date.setDate(QDate.currentDate())
        self.shift_date.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        shift_date_label = QLabel('Дата')
        date_layout.addWidget(shift_date_label)
        date_layout.addWidget(self.shift_date)
        
        time_from_layout = QHBoxLayout()
        self.shift_time_from = QTimeEdit()
        self.shift_time_from.setTime(QTime.currentTime())
        self.shift_time_from.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        shift_time_from_label = QLabel('Начало')
        time_from_layout.addWidget(shift_time_from_label)
        time_from_layout.addWidget(self.shift_time_from)
        time_to_layout = QHBoxLayout()
        self.shift_time_to = QTimeEdit()
        self.shift_time_to.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        shift_time_to_label = QLabel('Конец')
        time_to_layout.addWidget(shift_time_to_label)
        time_to_layout.addWidget(self.shift_time_to)
        
        create_shift_btn = QPushButton('Создать')
        create_shift_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        create_shift_btn.clicked.connect(self._create_shift)
        
        
        data_layout = QVBoxLayout()
        data_layout.addLayout(date_layout)            
        data_layout.addLayout(time_from_layout)
        data_layout.addLayout(time_to_layout)
        data_layout.addWidget(create_shift_btn)
        data_widget = QWidget()
        data_widget.setLayout(data_layout)
        data_widget.setFixedSize(QSize(400, 300))
        data_widget.setStyleSheet('background-color: rgb(118, 227, 131); color: #000;')
        layout = QHBoxLayout()
        layout.addWidget(get_logo())
        layout.addWidget(data_widget)
        
        self.create_shift_window.setLayout(layout)
        self.create_shift_window.setStyleSheet('background-color: #fff; color: #000;')
        self.create_shift_window.show()
                
    def _create_shift(self):
        if self.shift_date.date().toPython() < datetime.date.today():
            QMessageBox.warning(self, 'Ошибка', 'Нельзя создать смену в прошлом')
            return
        if self.shift_time_from.time().toPython() >= self.shift_time_to.time().toPython():
            QMessageBox.warning(self, 'Ошибка', 'Начало смены должно быть раньше конца')
            return
        Shift.create(date=self.shift_date.date().toPython(), start_time=self.shift_time_from.time().toPython(), end_time=self.shift_time_to.time().toPython())
        self._init_shifts_table()
        self.create_shift_window.close()
    
    def _assign_shift_window(self):
        selected_rows = self.shifts_table.selectedIndexes()
        if len(selected_rows) != 3:
            QMessageBox.warning(self, 'Ошибка', 'Выберите смену')
            return
        row = selected_rows[0].row()
        date = self.shifts_table.item(row, 0).text()
        time_to = self.shifts_table.item(row, 2).text()
        if datetime.datetime.strptime(date, '%d.%m.%Y').date() < datetime.date.today() or (datetime.datetime.strptime(time_to, '%H:%M').time() < datetime.datetime.now().time() and datetime.datetime.strptime(date, '%d.%m.%Y').date() == datetime.date.today()):
            QMessageBox.warning(self, 'Ошибка', 'Нельзя назначить смену в прошлом')
            return
        
        shift = Shift.select()[row]
        
        self.assign_shift_window = QWidget()
        self.assign_shift_window.setWindowTitle('Назначить смену')
        self.assign_shift_window.setWindowModality(Qt.ApplicationModal)
        
        shift_users_table = QTableWidget()
        shift_users_table.setColumnCount(2)
        shift_users_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        shift_users_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        shift_users_table.setHorizontalHeaderLabels(['Имя', 'Роль'])
        shift_users_table.setStyleSheet('background-color: rgb(118, 227, 131); color: #000;')
        back_btn = QPushButton('Назад')
        back_btn.clicked.connect(self.assign_shift_window.close)
        back_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')        
        
        users = shift.cooks
        shift_users_table.setRowCount(len(users))
        for i, row in enumerate(users):
            r = [row.username, row.role]
            for j, col in enumerate(r):
                shift_users_table.setItem(i, j, QTableWidgetItem(str(col)))
                
        usernames = [user.username for user in users]
        
        add_user_to_shift_layout = QHBoxLayout()
        add_user_to_shift_choose = QComboBox()
        add_user_to_shift_choose.addItems(self._get_logins_to_shift())
        add_user_to_shift_choose.setCurrentIndex(0)
        add_user_to_shift_btn = QPushButton('Назначить')
        add_user_to_shift_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        add_user_to_shift_btn.clicked.connect(lambda: self._add_user_to_shift(add_user_to_shift_choose.currentText(), shift) if add_user_to_shift_choose.currentText() not in usernames else QMessageBox.warning(self, 'Ошибка', 'Пользователь уже назначен на смену'))
        
        add_user_to_shift_layout.addWidget(add_user_to_shift_choose)
        add_user_to_shift_layout.addWidget(add_user_to_shift_btn)
        
        assign_layout = QVBoxLayout()
        assign_layout.addWidget(shift_users_table)
        assign_layout.addLayout(add_user_to_shift_layout)
        assign_layout.addWidget(back_btn)
        
        layout = QHBoxLayout()
        layout.addWidget(get_logo())
        layout.addLayout(assign_layout)
        
        self.assign_shift_window.setStyleSheet('background-color: #fff; color: #000;')
        self.assign_shift_window.setLayout(layout)
        self.assign_shift_window.show()
    
    def _add_user_to_shift(self, username: str, shift: Shift):
        user = User.get(User.username == username)
        if user.role == 'cook':
            shift.cooks.add(user)
        else:
            shift.waiters.add(user)
        shift.save()
        self.assign_shift_window.close()
        self._assign_shift_window()
    
    def _get_logins_to_shift(self):
        users = User.select(User.username).where((User.fired == False) & (User.role != 'admin'))
        return [user.username for user in users]
    
    def _init_orders_table(self):
        self.orders_table.clear()
        self.orders_table.setHorizontalHeaderLabels(['Номер стола', 'Количество гостей', 'Предметы', 'Статус', 'Официант'])
        orders = Order.select()
        db.close()
        self.orders_table.setRowCount(len(orders))
        for i, row in enumerate(orders):
            r = [row.table_number, row.num_guests, row.items, order_statuses[row.status], row.waiter.username]
            for j, col in enumerate(r):
                self.orders_table.setItem(i, j, QTableWidgetItem(str(col)))
        self.orders_table.resizeRowsToContents()
    
    def _init_shifts_table(self):
        self.shifts_table.clear()
        self.shifts_table.setHorizontalHeaderLabels(['Дата', 'Начало', 'Конец'])
        shifts = Shift.select()
        db.close()
        self.shifts_table.setRowCount(len(shifts))
        for i, row in enumerate(shifts):
            r = [datetime.datetime.strftime(row.date, '%d.%m.%Y'), row.start_time.strftime('%H:%M'), row.end_time.strftime('%H:%M')]
            for j, col in enumerate(r):
                self.shifts_table.setItem(i, j, QTableWidgetItem(str(col)))
                
    def _add_new_user_window(self):
        self.user_add_window = QWidget()
        self.user_add_window.setFixedSize(QSize(1000, 800))
        self.user_add_window.setWindowModality(Qt.ApplicationModal)
        self.user_add_window.setWindowTitle('Новый пользователь')
        user_add_layout = QVBoxLayout()
        login = QLineEdit()
        login.setPlaceholderText('Логин')
        login.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        password = QLineEdit()
        password.setPlaceholderText('Пароль')
        password.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        role = QComboBox()
        role.addItems(['admin', 'cook', 'waiter'])
        role.setCurrentIndex(0)
        role.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        add_btn = QPushButton('Добавить')
        add_btn.clicked.connect(lambda: self._add_new_user(login.text(), password.text(), role.currentText()))
        add_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        back_btn = QPushButton('Назад')
        back_btn.clicked.connect(self.user_add_window.close)
        back_btn.setStyleSheet('background-color: rgb(118, 227, 131); color: #000;')
        
        user_add_layout.addWidget(login)
        user_add_layout.addWidget(password)
        user_add_layout.addWidget(role)
        user_add_layout.addWidget(add_btn)
        user_add_layout.addWidget(back_btn)
        
        user_add_widget = QWidget(self.user_add_window)
        user_add_widget.setLayout(user_add_layout)
        user_add_widget.setFixedSize(QSize(400,300))
        user_add_widget.setStyleSheet('background-color: rgb(118, 227, 131); color: #000;')
        layout = QHBoxLayout()
        layout.addWidget(get_logo())
        layout.addWidget(user_add_widget)
        
        self.user_add_window.setLayout(layout)
        self.user_add_window.setStyleSheet('background-color: #fff; color: #000;')
        self.user_add_window.show()
        
    def _add_new_user(self, login, password, role):
        if login == '' or password == '':
            message_box = QMessageBox()
            message_box.setWindowTitle('Ошибка!')
            message_box.setText('Заполните все поля!')
            message_box.setIcon(QMessageBox.Icon.Warning)
            message_box.exec()
            return
        try:
            User.create(username=login, password=password, role=role)
            db.close()
            self._init_users_table()
            self.user_add_window.close()
        except Exception as e:
            db.close()
            message_box = QMessageBox()
            message_box.setWindowTitle('Ошибка!')
            message_box.setText('Пользователь с таким логином уже существует')
            message_box.setIcon(QMessageBox.Icon.Warning)
            message_box.exec()
        
    def _get_logins(self):
        users = User.select(User.username).where((User.fired == False) & (User != self.main_window.user))
        db.close()
        return users
    
    def _fire_user(self):
        selected_rows = self.users_table.selectedIndexes()
        if len(selected_rows) != 3:
            QMessageBox.warning(self, 'Error', 'Сначала выберите одну строку с пользователем!')
            return
        row = selected_rows[0].row()
        username = self.users_table.item(row, 0).text()
        if username == self.main_window.user.username:
            QMessageBox.warning(self, 'Error', 'Нельзя уволить себя!')
            return
        if self.users_table.item(row, 2).text() == 'True':
            QMessageBox.warning(self, 'Error', 'Нельзя уволить уволенного сотрудника!')
            return
        user = User.get(User.username==username)
        user.fired = True
        user.save()
        self._init_users_table()
        
    
    def _on_user_selected(self):
        selected_rows = self.users_table.selectedIndexes()
        if len(selected_rows) == 3:
            row = selected_rows[0].row()
            username = self.users_table.item(row, 0).text()
    
class CookWindow(QWidget):
    def __init__(self, parent):
        super().__init__()
        self.main_window = parent
        self.setWindowTitle('Окно повара')
        self.setMinimumSize(QSize(1000, 800))
        self.setWindowModality(Qt.ApplicationModal)
        
        self.orders_table = QTableWidget()
        self.orders_table.setColumnCount(4)
        self.orders_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.orders_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.orders_table.setHorizontalHeaderLabels(['Номер стола', 'Количество гостей', 'Состав', 'Статус'])
        self.orders_table.setStyleSheet('background-color: rgb(118, 227, 131); color: #000;')

        self.accept_order_btn = QPushButton('Готовится')
        self.accept_order_btn.clicked.connect(self._accepted_order)
        self.accept_order_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        
        self.ready_order_btn = QPushButton('Готов')
        self.ready_order_btn.clicked.connect(self._ready_order)
        self.ready_order_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')

        data_layout = QVBoxLayout()
        data_layout.addWidget(self.orders_table)
        data_layout.addWidget(self.accept_order_btn)
        data_layout.addWidget(self.ready_order_btn)
        
        exit_btn = QPushButton('Выход')
        exit_btn.clicked.connect(self._exit)
        data_layout.addWidget(exit_btn)
        
        
        layout = QHBoxLayout()
        layout.addWidget(get_logo())
        layout.addLayout(data_layout)

        self.setLayout(layout)
        self.setStyleSheet('background-color: #fff; color: #000;')
        self._init_orders_table()
    
    def _exit(self):
        self.main_window.show()
        self.close()

    def _init_orders_table(self):
        orders: List[Order] = Order.select().order_by(Order.id)
        self.orders_table.setRowCount(len(orders))
        for i, order in enumerate(orders):
            r = [order.table_number, order.num_guests, order.items, order_statuses[order.status]]
            for j, col in enumerate(r):
                self.orders_table.setItem(i, j, QTableWidgetItem(str(col)))
        self.orders_table.resizeRowsToContents()
        db.close()    
    
    def _accepted_order(self):
        selected_rows = self.orders_table.selectedIndexes()
        if len(selected_rows) != 4:
            QMessageBox.warning(self, 'Ошибка', 'Сначала выберите заказ')
            return
        row = selected_rows[0].row()
        order = Order.get(Order.id==row+1)
        if order.status == 'ready':
            QMessageBox.warning(self, 'Ошибка', 'Заказ уже готов')
            return
        order.status = 'preparing'
        order.save()
        self._init_orders_table()
        
    def _ready_order(self):
        selected_rows = self.orders_table.selectedIndexes()
        if len(selected_rows) != 4:
            QMessageBox.warning(self, 'Ошибка', 'Сначала выберите заказ')
            return
        row = selected_rows[0].row()
        order = Order.get(Order.id==row+1)
        if order.status == 'ready':
            QMessageBox.warning(self, 'Ошибка', 'Заказ уже готов')
            return
        order.status = 'ready'
        order.save()
        self._init_orders_table()    
    
class WaiterWindow(QWidget):
    def __init__(self, parent):
        super().__init__()
        self.main_window = parent
        self.setWindowTitle('Окно официанта')
        self.setMinimumSize(QSize(1000,800))
        self.setWindowModality(Qt.ApplicationModal)
        
        self.orders_table = QTableWidget()
        self.orders_table.setColumnCount(4)
        self.orders_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.orders_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.orders_table.setHorizontalHeaderLabels(['Номер стола', 'Количество гостей', 'Состав', 'Статус'])
        self.orders_table.setStyleSheet('background-color: rgb(118, 227, 131); color: #000;')
        
        self.add_order_btn = QPushButton('Новый заказ')
        self.add_order_btn.clicked.connect(self._add_order)
        self.add_order_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')

        self.pay_order_btn = QPushButton('Оплатить')
        self.pay_order_btn.clicked.connect(self._pay_order)
        self.pay_order_btn.setStyleSheet('background-color: rgb(153, 102, 51); color: #000;')
        
        

        data_layout = QVBoxLayout()
        data_layout.addWidget(self.orders_table)
        data_layout.addWidget(self.add_order_btn)
        data_layout.addWidget(self.pay_order_btn)
        
        exit_btn = QPushButton('Выход')
        exit_btn.clicked.connect(self._exit)
        data_layout.addWidget(exit_btn)
        
        layout = QHBoxLayout()
        layout.addWidget(get_logo())
        layout.addLayout(data_layout)

        self.setLayout(layout)
        self.setStyleSheet('background-color: #fff; color: #000;')
        self._init_orders_table()

    def _init_orders_table(self):
        orders: List[Order] = Order.select().order_by(Order.id)
        self.orders_table.setRowCount(len(orders))
        for i, order in enumerate(orders):
            r = [order.table_number, order.num_guests, order.items, order_statuses[order.status]]
            for j, col in enumerate(r):
                self.orders_table.setItem(i, j, QTableWidgetItem(str(col)))
        self.orders_table.resizeRowsToContents()
        db.close()
    
    def _exit(self):
        self.main_window.show()
        self.close()

    def _add_order(self):
        dialog = QInputDialog()
        table_number, ok = dialog.getInt(self, 'Новый заказ', 'Номер стола:')
        if not ok:
            return
        num_guests, ok = dialog.getInt(self, 'Новый заказ', 'Количество гостей:')
        if not ok:
            return
        date = datetime.date.today()
        items, ok = dialog.getMultiLineText(self, 'Новый заказ', 'Состав:')
        if not ok:
            return
        status = 'placed'
        order = Order(table_number=table_number, num_guests=num_guests, items=items, status=status, waiter=self.main_window.user)
        order.save()
        self._init_orders_table()

    def _pay_order(self):
        selected_rows = self.orders_table.selectedIndexes()
        if len(selected_rows) != 4:
            QMessageBox.warning(self, 'Ошибка', 'Сначала выберите заказ')
            return
        row = selected_rows[0].row()
        order = Order.get(Order.id==row+1)
        if order.status == 'paid':
            QMessageBox.warning(self, 'Ошибка', 'Заказ уже оплачен')
            return
        order.status = 'paid'
        order.save()
        self._init_orders_table()
        

if __name__=='__main__':
    db.connect()
    db.create_tables([User, Shift, Order, Shift.waiters.get_through_model(), Shift.cooks.get_through_model()])
    db.close()
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.setWindowIcon(QIcon('./Sezon.png'))
    sys.exit(app.exec())
